package com.fwtai.datasource;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.scripting.defaults.DefaultParameterHandler;

import java.sql.Connection;
import java.util.HashMap;
import java.util.Properties;
import java.util.regex.Pattern;

/**拦截器*/
@Intercepts({@Signature(type= StatementHandler.class,method="prepare",args={Connection.class,Integer.class})})
public class MybatisInterceptor implements Interceptor{

  @Override
  public Object intercept(final Invocation invocation) throws Throwable{
    return invocation.proceed();
  }

  @Override
  public Object plugin(final Object target){
    if(target instanceof DefaultParameterHandler){
      final DefaultParameterHandler parameter = (DefaultParameterHandler)target;
      final Object object = parameter.getParameterObject();
      if(object instanceof HashMap){
        final HashMap map = (HashMap) object;
        for(final Object key : map.keySet()){
          final Object obj = map.get(key);
          if(obj instanceof String){
            final String value = (String)obj;
            map.put(key,getLong(value));
          }
        }
      }
      if(object instanceof String){
        final String value = (String) object;
        if(value.length() > 16){
          return getLong(value);//处理手机号的问题
        }
      }
    }
    return target;
  }

  private Object getLong(final String value){
    try {
      final boolean b = Pattern.compile("[\\d]*$").matcher(value).matches();
      if(b){
        final int length = value.length();
        if(length > 16){
          return Long.parseLong(value);
        }
      }
    } catch (final Exception ignored){}
    return value;
  }

  @Override
  public void setProperties(final Properties properties){
    Interceptor.super.setProperties(properties);
  }
}